<template>
  <div class="wrap">
    <div class="wrap-button">
      <a-button style="margin-right: 8px" type="primary" @click="showAddModal">新增</a-button>
      <div style="float: right">
        <a-input
          v-model:value="pageParam.query.keyword"
          style="width: 180px; margin-right: 8px"
          placeholder="输入关键字查询"
          allow-clear
        >
          <template #prefix>
            <SearchOutlined style="color: #666" />
          </template>
        </a-input>
        <a-button type="primary" @click="list">查询</a-button>
      </div>
    </div>
    <div class="wrap-table">
      <a-table
        :loading="loading"
        :dataSource="data"
        :columns="columns"
        size="middle"
        @change="handleTableChange"
        width="300"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'operation'">
            <a-button
              class="button-interval"
              type="link"
              :icon="h(EditOutlined)"
              @click="showEditModal(record)"
              size="small"
            >
              修改
            </a-button>
          </template>
        </template>
      </a-table>
      <a-modal
        v-model:visible="open"
        :title="type === 'add' ? '新增租户' : '修改租户'"
        @ok="handleSubmit"
      >
        <a-form
          ref="formRef"
          style="margin-top: 24px"
          :model="formState"
          name="basic"
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 16 }"
          autocomplete="off"
        >
          <a-form-item
            label="租户名称"
            name="name"
            :rules="[{ required: true, message: 'Please input tenant name!' }]"
          >
            <a-input
              readOnly
              onfocus="this.removeAttribute('readonly');"
              onblur="this.setAttribute('readonly',true);"
              v-model:value="formState.name"
            />
          </a-form-item>
          <a-form-item label="负责人" name="manager">
            <a-input v-model:value="formState.manager" />
          </a-form-item>
          <a-form-item label="联系方式" name="managerTel">
            <a-input v-model:value="formState.managerTel" />
          </a-form-item>
          <a-form-item label="使用期限" name="licenseLimit">
            <a-input v-model:value="formState.licenseLimit" />
          </a-form-item>
          <a-form-item label="appKey" name="appKey">
            <a-input v-model:value="formState.appKey" />
          </a-form-item>
          <a-form-item label="appSecret" name="appSecret">
            <a-input v-model:value="formState.appSecret" />
          </a-form-item>
        </a-form>
      </a-modal>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { h, ref, unref, onMounted, reactive, computed, ComputedRef } from 'vue'
  import { EditOutlined, SearchOutlined } from '@ant-design/icons-vue'
  import { FormInstance, message } from 'ant-design-vue'
  import { TenantModel } from '/@/api/sys/model/tenantModel'
  import { pageTenant, createTenant, editTenant } from '/@/api/sys/tenant'
  import { BasicPageParams } from '/@/api/model/baseModel'

  const open = ref<boolean>(false)
  const loading = ref(false)
  const keyword = ref<string>('')
  const type = ref<string>('')

  const columns = [
    {
      title: '租户名称',
      dataIndex: 'name',
      key: 'name',
      align: 'center',
    },
    {
      title: '负责人',
      dataIndex: 'manager',
      key: 'manager',
      align: 'center',
    },
    {
      title: '联系方式',
      dataIndex: 'managerTel',
      key: 'managerTel',
      align: 'center',
    },
    {
      title: '使用期限',
      dataIndex: 'licenseLimit',
      key: 'licenseLimit',
      align: 'center',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      align: 'center',
    },
    {
      title: '操作',
      key: 'operation',
      fixed: 'right',
      align: 'center',
      width: 240,
    },
  ]

  let data = ref<TenantModel[]>([])

  const pagination = ref({
    total: 0,
    current: 1,
    pageSize: 10,
    size: '',
    showSizeChanger: false,
    showQuickJumper: false,
  })

  const pageParam = computed(() => ({
    query: {
      keyword: '',
    },
    current: pagination.value?.current,
    size: pagination.value?.pageSize,
  }))
  //#endregion

  onMounted(() => {
    list()
  })

  function handleTableChange(page) {
    pagination.value.current = page.current
    list()
  }

  async function list() {
    loading.value = true
    const res = await pageTenant(unref(pageParam)).finally(() => (loading.value = false))
    data.value = res.records
    pagination.value.total = Number(res.total)
    pagination.value.current = Number(res.current)
  }

  //#region

  const formRef = ref<FormInstance>()

  let formState = reactive<TenantModel>({
    name: '',
    manager: '',
    managerTel: '',
    appKey: '',
    appSecret: '',
    licenseLimit: '',
  })

  const handleSubmit = () => {
    if (type.value === 'add') {
      handleAddSubmit()
    } else {
      handleEditSubmit()
    }
  }

  const showAddModal = () => {
    open.value = true
    type.value = 'add'
    formRef.value?.resetFields()
  }

  const handleAddSubmit = () => {
    formRef.value
      ?.validateFields()
      .then(() => {
        createTenant(formState).then(() => {
          message.success('新增成功')
          open.value = false
          list()
        })
      })
      .catch(() => {
        message.error('表单填写错误')
      })
  }

  const showEditModal = (record) => {
    open.value = true
    type.value = 'edit'
    formState = JSON.parse(JSON.stringify(record))
    formRef.value?.resetFields()
  }

  const handleEditSubmit = () => {
    formRef.value
      ?.validateFields()
      .then(() => {
        editTenant(formState).then(() => {
          message.success('修改成功')
          open.value = false
          list()
        })
      })
      .catch(() => {
        message.error('表单填写错误')
      })
  }
</script>

<style lang="scss" scoped>
  .wrap {
    &-table {
      margin-top: 16px;
    }
  }
</style>
